package com.ruoyi.purchase.service.impl;

import java.util.Date;
import java.util.List;
import java.math.BigDecimal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.purchase.mapper.ProcOrderMapper;
import com.ruoyi.purchase.domain.ProcOrder;
import com.ruoyi.purchase.domain.ProcOrderExecution;
import com.ruoyi.purchase.service.IProcOrderService;
import com.ruoyi.purchase.service.IProcOrderExecutionService;
import com.ruoyi.api.event.EventPublisher;
import com.ruoyi.api.event.OrderExecutionEvent;
import com.ruoyi.api.event.EventType;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.StringBuilder;

/**
 * 采购订单主Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-06-17
 */
@Service
public class ProcOrderServiceImpl implements IProcOrderService 
{
    private static final Logger logger = LoggerFactory.getLogger(ProcOrderServiceImpl.class);
    
    @Autowired
    private ProcOrderMapper procOrderMapper;
    
    @Autowired
    private IProcOrderExecutionService procOrderExecutionService;
    
    @Autowired
    private EventPublisher eventPublisher;

    /**
     * 查询采购订单主
     * 
     * @param orderId 采购订单主主键
     * @return 采购订单主
     */
    @Override
    public ProcOrder selectProcOrderByOrderId(Long orderId)
    {
        return procOrderMapper.selectProcOrderByOrderId(orderId);
    }

    /**
     * 查询采购订单主列表
     * 
     * @param procOrder 采购订单主
     * @return 采购订单主
     */
    @Override
    public List<ProcOrder> selectProcOrderList(ProcOrder procOrder)
    {
        return procOrderMapper.selectProcOrderList(procOrder);
    }

    /**
     * 新增采购订单主
     * 
     * @param procOrder 采购订单主
     * @return 结果
     */
    @Override
    public int insertProcOrder(ProcOrder procOrder)
    {
        // 新增订单默认为待审核状态
        procOrder.setStatus("0"); // 订单状态为待审核
        procOrder.setAuditStatus("0"); // 审核状态为未审核
        return procOrderMapper.insertProcOrder(procOrder);
    }

    /**
     * 修改采购订单主
     * 
     * @param procOrder 采购订单主
     * @return 结果
     */
    @Override
    public int updateProcOrder(ProcOrder procOrder)
    {
        return procOrderMapper.updateProcOrder(procOrder);
    }

    /**
     * 批量删除采购订单主
     * 
     * @param orderIds 需要删除的采购订单主主键
     * @return 结果
     */
    @Override
    public int deleteProcOrderByOrderIds(String orderIds)
    {
        return procOrderMapper.deleteProcOrderByOrderIds(Convert.toStrArray(orderIds));
    }

    /**
     * 删除采购订单主信息
     * 
     * @param orderId 采购订单主主键
     * @return 结果
     */
    @Override
    public int deleteProcOrderByOrderId(Long orderId)
    {
        return procOrderMapper.deleteProcOrderByOrderId(orderId);
    }
    
    /**
     * 审核通过采购订单
     * 
     * @param orderId 订单ID
     * @param auditOpinion 审核意见
     * @return 结果
     */
    @Override
    public int approveOrder(Long orderId, String auditOpinion)
    {
        ProcOrder order = selectProcOrderByOrderId(orderId);
        order.setStatus("1"); // 设置订单状态为已审核
        order.setAuditStatus("1"); // 设置审核状态为审核通过
        order.setAuditOpinion(auditOpinion);
        order.setUpdateBy(ShiroUtils.getLoginName());
        return updateProcOrder(order);
    }
    
    /**
     * 审核拒绝采购订单
     * 
     * @param orderId 订单ID
     * @param auditOpinion 审核意见
     * @return 结果
     */
    @Override
    public int rejectOrder(Long orderId, String auditOpinion)
    {
        ProcOrder order = selectProcOrderByOrderId(orderId);
        order.setStatus("1"); // 订单状态改为已审核
        order.setAuditStatus("2"); // 设置审核状态为审核不通过
        order.setAuditOpinion(auditOpinion);
        order.setUpdateBy(ShiroUtils.getLoginName());
        return updateProcOrder(order);
    }
    
    /**
     * 执行采购订单
     * 
     * @param orderId 订单ID
     * @param executionRemark 执行备注
     * @return 结果
     */
    @Override
    @Transactional
    public int executeOrder(Long orderId, String executionRemark)
    {
        // 默认使用账户ID为1的账户
        return executeOrder(orderId, executionRemark, 1L);
    }
    
    @Override
    @Transactional
    public int executeOrder(Long orderId, String executionRemark, Long accountId)
    {
        // 1. 获取订单信息
        ProcOrder order = selectProcOrderByOrderId(orderId);
        if (order == null || !"1".equals(order.getAuditStatus()))
        {
            // 只有审核通过的订单才能执行
            return 0;
        }
        
        // 2. 更新订单状态为已执行
        order.setStatus("2"); // 订单状态改为已执行
        order.setUpdateBy(ShiroUtils.getLoginName());
        int rows = updateProcOrder(order);
        
        if (rows > 0)
        {
            // 3. 添加订单执行记录
            ProcOrderExecution execution = new ProcOrderExecution();
            execution.setOrderId(orderId);
            execution.setExecutionDate(DateUtils.getNowDate());
            execution.setExecutor(ShiroUtils.getLoginName());
            execution.setExecutionRemark(executionRemark);
            execution.setCreatedTime(DateUtils.getNowDate());
            procOrderExecutionService.insertProcOrderExecution(execution);
            
            // 4. 发布采购订单执行事件，而不是直接调用财务服务
            OrderExecutionEvent event = new OrderExecutionEvent(EventType.PURCHASE_ORDER_EXECUTED, orderId);
            event.setOrderCode(order.getOrderCode());
            event.setTotalAmount(order.getTotalAmount());
            event.addData("supplierName", order.getSupplierName());
            event.addData("supplierId", order.getSupplierId());
            // 添加账户ID
            event.addData("accountId", accountId);
            
            // 添加商品ID和采购数量，用于库存更新
            event.addData("productId", order.getProductId());
            event.addData("quantity", order.getQuantity());
            // 添加商品名称
            event.addData("productName", order.getProductName());
            
            eventPublisher.publishEvent(event);
        }
        
        return rows;
    }
    
    /**
     * 批量执行所有审核通过的采购订单
     * 
     * @param executionRemark 执行备注
     * @param accountId 财务账户ID
     * @return 成功执行的订单数量
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int executeAllApprovedOrders(String executionRemark, Long accountId)
    {
        if (accountId == null) {
            logger.error("批量执行采购订单失败：账户ID不能为空");
            throw new RuntimeException("账户ID不能为空");
        }
        
        // 查询所有审核通过但未执行的订单
        ProcOrder queryOrder = new ProcOrder();
        queryOrder.setAuditStatus("1"); // 审核状态为审核通过
        queryOrder.setStatus("1"); // 订单状态为已审核（未执行）
        
        List<ProcOrder> approvedOrders = procOrderMapper.selectProcOrderList(queryOrder);
        
        if (approvedOrders == null || approvedOrders.isEmpty()) {
            logger.info("没有符合条件的采购订单需要执行");
            return 0;
        }
        
        logger.info("开始批量执行采购订单，共{}个订单", approvedOrders.size());
        
        int successCount = 0;
        StringBuilder errorMsgs = new StringBuilder();
        
        // 逐个执行订单
        for (ProcOrder order : approvedOrders)
        {
            try
            {
                logger.info("执行采购订单：ID={}, 编号={}", order.getOrderId(), order.getOrderCode());
                int result = executeOrder(order.getOrderId(), executionRemark, accountId);
                if (result > 0)
                {
                    successCount++;
                    logger.info("采购订单执行成功：ID={}, 编号={}", order.getOrderId(), order.getOrderCode());
                } else {
                    logger.warn("采购订单执行失败：ID={}, 编号={}", order.getOrderId(), order.getOrderCode());
                    errorMsgs.append("订单[").append(order.getOrderCode()).append("]执行失败; ");
                }
            }
            catch (Exception e)
            {
                logger.error("执行采购订单异常：ID={}, 编号={}, 错误={}", order.getOrderId(), order.getOrderCode(), e.getMessage(), e);
                errorMsgs.append("订单[").append(order.getOrderCode()).append("]执行异常: ").append(e.getMessage()).append("; ");
                // 继续执行下一个订单
            }
        }
        
        if (errorMsgs.length() > 0 && successCount < approvedOrders.size()) {
            logger.warn("部分采购订单执行失败：{}", errorMsgs.toString());
        }
        
        logger.info("批量执行采购订单完成，成功{}个，失败{}个", 
                successCount, approvedOrders.size() - successCount);
        
        return successCount;
    }

    /**
     * 批量审核通过采购订单
     * 
     * @param orderIds 订单ID数组
     * @param auditOpinion 审核意见
     * @return 结果
     */
    @Override
    public int batchApproveOrders(String orderIds, String auditOpinion) {
        String[] ids = Convert.toStrArray(orderIds);
        int successCount = 0;
        
        for (String orderId : ids) {
            try {
                Long id = Long.valueOf(orderId);
                int result = approveOrder(id, auditOpinion);
                if (result > 0) {
                    successCount++;
                }
            } catch (Exception e) {
                logger.error("批量审核通过订单失败，订单ID: " + orderId, e);
            }
        }
        
        return successCount;
    }
    
    /**
     * 批量审核拒绝采购订单
     * 
     * @param orderIds 订单ID数组
     * @param auditOpinion 审核意见
     * @return 结果
     */
    @Override
    public int batchRejectOrders(String orderIds, String auditOpinion) {
        String[] ids = Convert.toStrArray(orderIds);
        int successCount = 0;
        
        for (String orderId : ids) {
            try {
                Long id = Long.valueOf(orderId);
                int result = rejectOrder(id, auditOpinion);
                if (result > 0) {
                    successCount++;
                }
            } catch (Exception e) {
                logger.error("批量审核拒绝订单失败，订单ID: " + orderId, e);
            }
        }
        
        return successCount;
    }
}

